package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.BusServiceItem;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.mapper.BusServiceItemMapper;
import cn.wolfcode.car.business.query.BusServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.IBusServiceItemService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Transactional
public class BusServiceItemServiceImpl implements IBusServiceItemService {

    @Autowired
    private BusServiceItemMapper busServiceItemMapper;
    @Autowired
    @Lazy
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;

    @Override
    public TablePageInfo<BusServiceItem> query(BusServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BusServiceItem>(busServiceItemMapper.selectForList(qo));
    }


    @Override
    public void save(BusServiceItem busServiceItem) {
        BusServiceItem serviceObj = new BusServiceItem();
        serviceObj.setName(busServiceItem.getName()); //服务项名称
        serviceObj.setOriginalPrice(busServiceItem.getOriginalPrice()); //服务项原价
        serviceObj.setDiscountPrice(busServiceItem.getDiscountPrice()); //服务项折扣价
        serviceObj.setCarPackage(busServiceItem.getCarPackage());//是否套餐【是/否】
        serviceObj.setServiceCatalog(busServiceItem.getServiceCatalog());//服务分类
        serviceObj.setInfo(busServiceItem.getInfo());//备注信息
        //判断是否为套餐
        if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())) {
            //是套餐
            serviceObj.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        } else {
            //不是套餐
            serviceObj.setAuditStatus(BusServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        busServiceItemMapper.insert(serviceObj);
    }

    @Override
    public BusServiceItem get(Long id) {
        return busServiceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(BusServiceItem busServiceItem) {

        BusServiceItem serviceObj1 = this.get(busServiceItem.getId());
        System.out.println(serviceObj1);

        //判断是否为上架
        if (BusServiceItem.SALESTATUS_ON.equals(serviceObj1.getSaleStatus())) {
            //是上架
            throw new BusinessException("该商品处于上架状态，不能修改");
        }
        if (BusServiceItem.AUDITSTATUS_AUDITING.equals(serviceObj1.getAuditStatus())) {
            //审核中
            throw new BusinessException("该商品处于审核状态，不能修改");
        }
        //是套餐且审核通过
        if (BusServiceItem.AUDITSTATUS_APPROVED.equals(serviceObj1.getAuditStatus())) {
            serviceObj1.setAuditStatus(BusServiceItem.AUDITSTATUS_INIT);
        }
        serviceObj1.setName(busServiceItem.getName()); //服务项名称
        serviceObj1.setOriginalPrice(busServiceItem.getOriginalPrice()); //服务项原价
        serviceObj1.setDiscountPrice(busServiceItem.getDiscountPrice()); //服务项折扣价
        serviceObj1.setServiceCatalog(busServiceItem.getServiceCatalog());//服务分类
        serviceObj1.setInfo(busServiceItem.getInfo());//备注信息1
        busServiceItemMapper.updateByPrimaryKey(serviceObj1);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            busServiceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<BusServiceItem> list() {
        return busServiceItemMapper.selectAll();
    }

    @Override
    public void changeStatus(Long serviceItemId, Integer status) {
        busServiceItemMapper.changeStatus(serviceItemId,status);
    }

    @Override
    public void startAudit(Long id, Long shopOwnerId, Long financialId, String info) {
        //有什么样的限制条件
           //根据服务单项的id查询服务单项，判断状态是否处于初始化状态或者从新调整
        BusServiceItem busServiceItem = this.get(id);
        if (BusServiceItem.AUDITSTATUS_INIT.equals(busServiceItem.getAuditStatus()) ||
                BusServiceItem.AUDITSTATUS_REPLY.equals(busServiceItem.getAuditStatus())) {
        //需要封装CarPackageAudit信息
            CarPackageAudit audit = new CarPackageAudit();
            audit.setServiceItemId(busServiceItem.getId());
            audit.setServiceItemName(busServiceItem.getName());
            audit.setServiceItemPrice(busServiceItem.getDiscountPrice());
            audit.setCreateTime(new Date());
            audit.setCreatorId(String.valueOf(ShiroUtils.getUserId()));
            audit.setInfo(info);
            carPackageAuditService.save(audit);
            //获取插入数据苦衷的id值
            String businessKey = String.valueOf(audit.getId());
            //如何找到对应流程定义，发起流程实例
          //通过CarPackageAudit.AUDIT_TYPE去bpmnInfo表中查询记录
          //如果有多个，就按照部署时间去最近的部署那个
            BpmnInfo bpmnInfo = bpmnInfoService.getByBpmnType(CarPackageAudit.AUDIT_TYPE);
          //如果查询返回为null，说明没有上传流程定义
            if (bpmnInfo == null) {
                throw new BusinessException("缺少流程定义，请联系管理员");
            }
            //流程定义key
            String processDefinitionKey = bpmnInfo.getProcessDefinitionKey();
            //发起流程的时候需要携带审核参数到流程中
            //需要定义Map集合 存储店长id，财务id，折扣金额
            HashMap<String, Object> params = new HashMap<>();
            params.put("shopOwnerId",shopOwnerId);
            params.put("financeId",financialId);
            params.put("disCountPrice",busServiceItem.getDiscountPrice());
            //启动流程实例，业务可以和流程变量在启动的时候一并传入
            ProcessInstance instance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, params);
            //服务单项的状态怎么改变
            //改成审核中
            busServiceItem.setAuditStatus(BusServiceItem.AUDITSTATUS_AUDITING);
            busServiceItemMapper.updateByPrimaryKey(busServiceItem);
        //CarPackageAudit信息需要设置instanceId???
            audit.setInstanceId(instance.getId());
            carPackageAuditService.update(audit);
        }else {
            throw new BusinessException("非法操作");
        }
    }

    @Override
    public void updateDeleteBatch(Long id) {
        BusServiceItem busServiceItem = this.get(id);
        //判断是否为上架

        if (BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())) {
            //是上架
            throw new BusinessException("该商品处于上架状态，不能删除");
        }
        if (BusServiceItem.AUDITSTATUS_AUDITING.equals(busServiceItem.getAuditStatus())) {
            //审核中
            throw new BusinessException("该商品处于审核状态，不能删除");
        }
        //busServiceItem.setIsDelete(BusServiceItem.DELETE_ON);
            busServiceItemMapper.updateDeleteBatch(busServiceItem.getId());
    }

    //下架
    @Override
    public void saleOff(Long id) {
        BusServiceItem busServiceItem = this.get(id);
        if (BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())) {
            busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_OFF);
            busServiceItemMapper.updateByPrimaryKey(busServiceItem);
        }
    }

    //上架
    @Override
    public void saleOn(Long id) {
        BusServiceItem busServiceItem = this.get(id);
        if (busServiceItem!=null) {
            //处于上架状态不管
            if (BusServiceItem.SALESTATUS_ON.equals(busServiceItem.getSaleStatus())) {
                throw new BusinessException("上架服务项目不能修改，请下架后再修改");
            }
            //套餐审核没有通过
            if (BusServiceItem.CARPACKAGE_YES.equals(busServiceItem.getCarPackage())//套餐
                    && !BusServiceItem.AUDITSTATUS_APPROVED.equals(busServiceItem.getAuditStatus())){
                throw new BusinessException("审核不通过的套餐不能上架");
            }
            //其他就可以上架
            busServiceItem.setSaleStatus(BusServiceItem.SALESTATUS_ON);
            busServiceItemMapper.updateByPrimaryKey(busServiceItem);
        }
    }
}
